//
//  PagedCollectionViewLayout.swift
//  LiveShow
//
//  Created by dai zhong on 2017/4/17.
//  Copyright © 2017年 company.cn. All rights reserved.
//

import UIKit

class PagedCollectionViewLayout: UICollectionViewFlowLayout {

    fileprivate var itemslayoutAttributes:[UICollectionViewLayoutAttributes] = [UICollectionViewLayoutAttributes]()
    fileprivate var pageCollectionStyle :PagedCollectionStyle!
    fileprivate var prePagesOfcurrentSection :NSInteger = 0;
    fileprivate var preSection : NSInteger = 0;
    
    convenience init(pageCollectionStyle style :PagedCollectionStyle) {
        self.init();
        self.pageCollectionStyle = style;
    }
}

// MARK:- Public Method
extension PagedCollectionViewLayout {

    public func numberOfPageInSection(InSection section  :NSInteger ) -> NSInteger{
    
        guard let targetCollectionView = collectionView else {
            return 0;
        }
        
        let numberOfItems = targetCollectionView.numberOfItems(inSection: section);
        return numberOfItems/(pageCollectionStyle.aPageColumnCount * pageCollectionStyle.aPageRowCout) + 1;
    }
}

// MARK:- 重载 UICollectionViewFlowLayout 的布局方法
extension PagedCollectionViewLayout{

   
    override func prepare() {
        
        super.prepare();
        setupIntialData();
        calculatLayoutAttributes();
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        return itemslayoutAttributes;
    }
    
    override var collectionViewContentSize: CGSize{
        return  CGSize(width: CGFloat(prePagesOfcurrentSection) * (collectionView?.bounds.width)!, height: 0);
    }

}

// MARK:- Public Method
extension PagedCollectionViewLayout{

    public func pageCountInSection(InSection section :NSInteger) -> NSInteger{
    
        guard let targetCollectionView = collectionView else {
            return 0;
        }
        let numberOfSections = targetCollectionView.numberOfSections;
        if section >= numberOfSections {
            return 0;
        }
        let numberOfItems = targetCollectionView.numberOfItems(inSection: section);
        return numberOfItems/(pageCollectionStyle.aPageColumnCount * pageCollectionStyle.aPageRowCout) + 1;
    }
    
    public func itemPageIndexInSection(at indexPath :IndexPath) ->NSInteger{
        
        return indexPath.row / (pageCollectionStyle.aPageRowCout * pageCollectionStyle.aPageColumnCount);
    }
    
    public func scrollToItem(at indexPath :IndexPath) ->CGPoint{
    
        var totalPages = 0;
        for i in 0..<indexPath.section{
            totalPages += self.pageCountInSection(InSection: i);
        }
        totalPages += self.itemPageIndexInSection(at: indexPath);
        return CGPoint(x: CGFloat(totalPages) * (collectionView?.bounds.width ?? 0), y: 0);
    }
}

// MARK:- 重写布局方法
extension PagedCollectionViewLayout{
    
    fileprivate func setupIntialData(){
    
        self.minimumLineSpacing = pageCollectionStyle.lineSpacing;
        self.minimumInteritemSpacing = pageCollectionStyle.interitemSpacing;
        self.sectionInset = pageCollectionStyle.edgInsets;
        self.itemSize = getItemSize();
        self.scrollDirection = .horizontal;
    }
    
    fileprivate func calculatLayoutAttributes(){
    
        guard let targetCollectionView = collectionView else {
            return ;
        }
        
        let numberOfSections = targetCollectionView.numberOfSections;
        for i in 0..<numberOfSections{
            
            let numberOfItems = targetCollectionView.numberOfItems(inSection: i);
            for j in 0..<numberOfItems{
            
                let indexPath = NSIndexPath(item: j, section: i);
                let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath as IndexPath)
                attr.frame = itemFrameAtIndexPath(at: indexPath as IndexPath);
                itemslayoutAttributes.append(attr);
            }
            let left = numberOfItems%(pageCollectionStyle.aPageColumnCount * pageCollectionStyle.aPageRowCout);
            prePagesOfcurrentSection += numberOfItems/(pageCollectionStyle.aPageColumnCount * pageCollectionStyle.aPageRowCout);
            prePagesOfcurrentSection += left > 0 ?1 :0
        }
    }
    
    fileprivate func itemIndexAtPageInSection(at indexPath :IndexPath) ->NSInteger{
        
        return indexPath.row % (pageCollectionStyle.aPageRowCout * pageCollectionStyle.aPageColumnCount);
    }
    
    fileprivate func getItemSize() ->CGSize{
    
        guard let targetCollectionView = collectionView else {
            return CGSize.zero;
        }
        
        let layoutAttributesW :CGFloat = (targetCollectionView.bounds.width - (pageCollectionStyle.edgInsets.left + pageCollectionStyle.edgInsets.right + pageCollectionStyle.interitemSpacing * CGFloat((pageCollectionStyle.aPageColumnCount - 1)))) / CGFloat(pageCollectionStyle.aPageColumnCount);
        
        let layoutAttributesH :CGFloat = (targetCollectionView.bounds.height - (pageCollectionStyle.edgInsets.top + pageCollectionStyle.edgInsets.bottom + pageCollectionStyle.lineSpacing * CGFloat((pageCollectionStyle.aPageRowCout - 1))))/CGFloat(pageCollectionStyle.aPageRowCout);
        
        return CGSize(width: layoutAttributesW, height: layoutAttributesH);
    }

    fileprivate func itemFrameAtIndexPath(at indexPath :IndexPath) -> CGRect{
    
        guard let targetCollectionView = collectionView else {
            return CGRect.zero;
        }
        
        let pageIndexInSection = itemPageIndexInSection(at: indexPath as IndexPath);
        let itemIndexInPage = itemIndexAtPageInSection(at: indexPath as IndexPath);
        
        let itemSize = getItemSize();
        let layoutAttributesW :CGFloat = itemSize.width;
        let layoutAttributesH :CGFloat = itemSize.height;
        let layoutAttributesY :CGFloat = pageCollectionStyle.edgInsets.top + (pageCollectionStyle.lineSpacing + layoutAttributesH)*CGFloat(itemIndexInPage / pageCollectionStyle.aPageColumnCount);
        let layoutAttributesX :CGFloat = (pageCollectionStyle.edgInsets.left + (pageCollectionStyle.interitemSpacing + layoutAttributesW)*CGFloat(itemIndexInPage % pageCollectionStyle.aPageColumnCount)) + CGFloat(pageIndexInSection + prePagesOfcurrentSection)*(targetCollectionView.bounds.width);
        
        let rect = CGRect(x: layoutAttributesX, y: layoutAttributesY, width: layoutAttributesW, height: layoutAttributesH);
        return rect;
    }
}


























